package top.hg.tool.modules.car.article;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import top.hg.tool.modules.car.constant.RedisKeyConstant;

import java.util.List;

/**
 * @Author: skh
 * @Date: 2019/7/18 10:32
 * @Description: 文章服务
 */
@Service
@Slf4j
public class ArticleService extends ServiceImpl<ArticleDao, ArticleEntity> {

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /*
    1.把文章无格式粘贴到word
    2.用notepad++替换换行符 \r->\\r \n->\\n
    3.使用接口保存数据到数据库
     */
    public Integer saveArticle(ArticleEntity articleEntity) {
        articleEntity.setReadCount(100);
        Integer id = articleRepository.saveArticle(articleEntity);
        //设置阅读量
        redisTemplate.opsForValue().set(RedisKeyConstant.car_article_read_count + id, String.valueOf(100));
        log.info("新增文章成功,文章id:{}", id);
        return id;
    }


    public List<ArticleEntity> getArticleList() {
        List<ArticleEntity> articleList = articleRepository.getArticleList();
        //设置阅读量
        for (ArticleEntity articleEntity : articleList) {
            String readCount = redisTemplate.opsForValue().get(RedisKeyConstant.car_article_read_count + articleEntity.getId());
            articleEntity.setReadCount(Integer.valueOf(readCount));
        }
        return articleList;
    }

    public ArticleEntity getArticleById(Integer id) {
        ArticleEntity articleById = articleRepository.getArticleById(id);
        //新增阅读量
        redisTemplate.opsForValue().increment(RedisKeyConstant.car_article_read_count + id);
        return articleById;
    }

    public void refreshArticleReadCount() {
        //查询所有文章
        List<ArticleEntity> articleList = articleRepository.getArticleList();
        for (ArticleEntity articleEntity : articleList) {
            String readCountStr = redisTemplate.opsForValue().get(RedisKeyConstant.car_article_read_count + articleEntity.getId());
            if (StrUtil.isBlank(readCountStr)) {
                continue;
            }
            Integer readCount = Integer.valueOf(readCountStr);
            if (readCount == 0) {
                continue;
            }
            articleEntity.setReadCount(readCount);
            articleRepository.updateArticleById(articleEntity);

        }

        log.info("刷新文章阅读数成功");
    }
}
